package com.demo.servlet;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.demo.bean.Category;
import com.demo.service.ICategoryService;
import com.demo.service.impl.CategoryServiceImpl;

/**
 * Servlet implementation class categoryServlet
 */
@WebServlet("/category")
public class CategoryServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	ICategoryService service = new CategoryServiceImpl();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CategoryServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String method = request.getParameter("method");

		if ("deleteCategory".equals(method)) {
			service.deleteById(Integer.parseInt(request.getParameter("id")));
		}

		int index = request.getParameter("currentPage") == null ? 1 : Integer.parseInt(request.getParameter("currentPage"));
		request.setAttribute("page", service.getPage(index - 1, 5));
		request.getRequestDispatcher("category-list.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		Category ca = new Category();
		ca.setCreateTime(new Date());
		ca.setC_name(request.getParameter("c_name"));
		ca.setPlace(request.getParameter("place"));
		ca.setType(Byte.valueOf(request.getParameter("type")));
		if ("updateCategory".equals(request.getParameter("method"))) {
			ca.setC_id(Integer.parseInt(request.getParameter("c_id")));
			service.update(ca);
			response.sendRedirect("/category");
			return;
		}
		if (service.add(ca)) {
			response.sendRedirect("/category");
			return;
		}
		response.getWriter().append("add category failure..");
	}

}
